package cn.loveq.android.manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import cn.loveq.android.util.Downloader;
import cn.loveq.android.util.ImageUtil;

public class EmotionManager {
	private Context mContext;
	private static final int HARD_CACHE_CAPACITY = 10;
	private final static ConcurrentHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>(
			HARD_CACHE_CAPACITY / 2);

	public EmotionManager(Context mContext) {
		super();
		this.mContext = mContext;
	}

	/**
	 * 
	 * loadEmotions(加载表情库)
	 * 
	 * @return String DOM对象
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	/*
	 * private void loadEmotions() { mHandler.post(new Runnable() {
	 * 
	 * @Override public void run() { if(emotionsList == null){ mContext.get } } }); }
	 */
	public SpannableString emotionConvert(String str) {
		SpannableString spannableString = new SpannableString(str);
		List<HashMap<String, String>> list = phrase(str);
		for (HashMap<String, String> map : list) {
			SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(map.get("phrase"));
			if (bitmapReference != null) {
				ImageSpan imageSpan = new ImageSpan(bitmapReference.get());
				spannableString.setSpan(imageSpan, Integer.parseInt(map.get("start")), Integer.parseInt(map.get("end")),
						SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
			} else {
				Bitmap bitmap = getImageFromFileCache(map.get("phrase") + ".gif");
				if (bitmap != null) {
					bitmap = ImageUtil.zoomBitmap(bitmap, 45, 45);
					
					ImageSpan imageSpan = new ImageSpan(bitmap);
					spannableString.setSpan(imageSpan, Integer.parseInt(map.get("start")), Integer.parseInt(map.get("end")),
							SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
					sSoftBitmapCache.put(map.get("phrase") , new SoftReference<Bitmap>(bitmap));
				}
			}
		}
		return spannableString;
	}

	
	public static InputStream getInputStream(String fileName) {

		try {
			InputStream inputStream = null;
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 内存卡存在
				File dir = new File(Downloader.SDCARD_PATH + "/" + Downloader.IMAGES_FILE_NAME);
				if (!dir.exists()) {
					dir.mkdirs();
				}

				File file = new File(Downloader.SDCARD_PATH + "/" + Downloader.IMAGES_FILE_NAME + "/" + fileName);
				inputStream = new FileInputStream(file);

			}
			return inputStream;
		} catch (FileNotFoundException e) {
			return null;
			// e.printStackTrace();
			// System.gc();
		} catch (Exception e) {
			System.gc();
		}

		return null;
	}

	public static Bitmap getImageFromFileCache(String filename) {
		InputStream is = null;
		try {
			is = getInputStream(filename);// 打开输入流
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			return bitmap;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * getImageFromAssetFile(从assert文件获取对应的表情)
	 * 
	 * @return String DOM对象
	 * @Exception 异常对象
	 * @since CodingExample　Ver(编码范例查看) 1.1
	 */
	private Bitmap getImageFromAssetFile(String fileName) {
		Bitmap image = null;
		try {
			AssetManager am = mContext.getAssets();
			InputStream is = am.open("icon.png");
			image = BitmapFactory.decodeStream(is);
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return image;
	}

	public List<HashMap<String, String>> phrase(String str) {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		Matcher matcher = Pattern.compile("\\[(.+)\\]").matcher(str);
		while (matcher.find()) {
			HashMap<String, String> map = new HashMap<String, String>();
			String phrase = matcher.group();
			Log.i("vita", "phrase = " + phrase.substring(1, phrase.length() - 1));
			map.put("phrase", phrase.substring(1, phrase.length() - 1));
			map.put("start", matcher.start() + "");
			map.put("end", matcher.end() + "");
			list.add(map);
		}

		return list;
	}
}
